import { useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import {
  Form,
  Input,
  Button,
  Radio,
  InputNumber,
  Upload,
  message,
  Modal,
} from 'antd';
import { addImg } from '../../apis/admin';
import { updateAdmin } from '../../apis/admin';
import { useLocation, useNavigate } from 'react-router-dom';
import { Tree } from 'antd';
import type { DataNode } from 'antd/es/tree';
import React, { useState } from 'react';
import menus, { MenuType } from '../../router/menus'
import { useAppSelector } from '../../store/hooks';


export const AddAdmin = () => {
  // const [imageUrl, setImageUrl] = useState<string>();
  const { state: { adminInfo } } = useLocation()
  const { state: { option } } = useLocation()
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [form] = Form.useForm();

  //树形控件
  const adminKeys = useAppSelector(state => state.user.checkedkeys)
  const [checkedKeys, setCheckedKeys] = useState(adminKeys);

  const treeData = getTreeData(menus)
  const navigate = useNavigate()


  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };


  const finish = (values: any) => {
    // console.log(values);

    // console.log("formValues", values);
    // const formData = new FormData();
    // console.log("fileList", fileList);


    // fileList.forEach(file => {
    //   formData.append('files', file as RcFile);
    // });
    // // setUploading(true);
    // console.log("formData", formData);

    // values["icon"] = imageUrl

    console.log(checkedKeys);

    values.checkedKeys = checkedKeys

    if (option === 'update') {
      updateAdmin(adminInfo.id, values).then(() => {
        setFileList([]);
        message.success('upload successfully.');
      })
        .catch(() => {
          message.error('upload failed.');
        })
    } else if (option === 'add') {
      addImg(values).then(() => {
        setFileList([]);
        message.success('upload successfully.');
      })
        .catch(() => {
          message.error('upload failed.');
        })
    }
    navigate('/admin/list', { replace: false })
  }

  // useEffect(() => {
  //   if (option === 'update') {
  //     setFileList(adminInfo.icon)
  //   }
  // }, [])

  const handleUpload = (info: UploadChangeParam<UploadFile>) => {
    console.log(info);
    console.log(info.fileList[0].originFileObj);

    setFileList(info.fileList)
    // getBase64(info.fileList[0].originFileObj as RcFile, url => {
    //   setImageUrl(url);
    // });

    return
  };


  const props: UploadProps = {
    onRemove: file => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    listType: "picture-card",
    beforeUpload: file => {
      setFileList([...fileList, file]);
      return false;
    },
  };

  interface ITreeData {
    key: string
    title: string
    children?: ITreeData[]
  }
  // 获取权限数组
  function getTreeData(menus: MenuType[]) {
    const arr: ITreeData[] = []
    menus.forEach(item => {
      let obj: ITreeData = {
        key: '',
        title: ''
      }
      if (item.children) {
        obj = {
          key: item.keyId,
          title: item.label,
          children: getTreeData(item.children)
        }
      } else {
        obj = {
          key: item.keyId,
          title: item.label,
        }
      }
      arr.push(obj)
    })
    return arr
  }
  //modal
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const onChecked = (checkedKeysValue: any) => {
    console.log('cheeeeck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };



  return (
    <>
      {
        console.log(option, adminInfo)
        // console.log(fileList)
      }
      {
        option === 'update' ?
          <Form
            labelCol={{ span: 4 }}
            onFinish={finish}
            scrollToFirstError={true}
            wrapperCol={{ span: 14 }}
            layout="horizontal"
          >

            <Form.Item name="user" initialValue={adminInfo.user} label="用户名" required={true}>
              <Input />
            </Form.Item>
            <Form.Item name="password" label="密码" initialValue={adminInfo.password} rules={[{ required: true }]}>
              <Input type='password' />
            </Form.Item>

            {/* <Form.Item label="性别">
              <Radio.Group name="gender"  defaultValue={adminInfo.gender}>
                <Radio value="male"> male </Radio>
                <Radio value="female"> female </Radio>
              </Radio.Group>
            </Form.Item> */}

            <Form.Item label="邮箱" name="email" initialValue={adminInfo.email} rules={[{ type: 'email' }]}>
              <Input />
            </Form.Item>


            <Form.Item label="用户角色" name="role" initialValue={adminInfo.role}>
              <InputNumber placeholder='0 或 1' />
            </Form.Item>
            <Form.Item
              name="icon"
              label="头像"
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }
              }
            >
              <Upload {...props}
                // defaultFileList={[...fileList]}
                fileList={[...fileList]}
                onChange={handleUpload}>
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              </Upload>
            </Form.Item>

            <Form.Item
              name="checkedkeys"
              label="管理员权限"
            >
              <Button type="primary" onClick={showModal}>
                更改权限
              </Button>
              <Modal title="修改用户权限" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Tree
                  checkable
                  defaultExpandAll
                  onCheck={onChecked}
                  checkedKeys={checkedKeys}
                  treeData={treeData}
                />
              </Modal>
            </Form.Item>

            <Form.Item label="操作">
              <Button htmlType="submit">{option === 'update' ? "修改" : "添加"}</Button>
            </Form.Item>
          </Form>
          : <Form
            labelCol={{ span: 4 }}
            onFinish={finish}
            scrollToFirstError={true}
            wrapperCol={{ span: 14 }}
            layout="horizontal"
          >

            <Form.Item name="user" label="用户名" required={true}>
              <Input />
            </Form.Item>
            <Form.Item name="password" label="密码" rules={[{ required: true, }]}>
              <Input type='password' />
            </Form.Item>

            {/* <Form.Item label="性别">
              <Radio.Group name="gender">
                <Radio value="apple"> male </Radio>
                <Radio value="pear"> female </Radio>
              </Radio.Group>
            </Form.Item> */}

            <Form.Item label="邮箱" name="email" rules={[{ type: 'email' }]}>
              <Input />
            </Form.Item>


            <Form.Item label="角色" name="role">
              <InputNumber />
            </Form.Item>
            <Form.Item
              name='icon'
              label="头像"
              valuePropName="fileList"
              getValueFromEvent={(e) => {
                if (Array.isArray(e)) {
                  return e;
                }
                return e && e.fileList;
              }
              }
            >
              <Upload {...props}
                fileList={fileList}
                onChange={handleUpload}
              >
                <div>
                  <PlusOutlined />
                  <div style={{ marginTop: 8 }}>Upload</div>
                </div>
              </Upload>
            </Form.Item>

            <Form.Item
              name="checkedkeys"
              label="管理员权限"
            >
              <Button type="primary" onClick={showModal}>
                更改权限
              </Button>
              <Modal title="添加用户权限" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
                <Tree
                  checkable
                  defaultExpandAll
                  onCheck={onChecked}
                  checkedKeys={checkedKeys}
                  treeData={treeData}
                />
              </Modal>
            </Form.Item>

            <Form.Item label="操作">
              <Button htmlType="submit">{option === 'update' ? "修改" : "添加"}</Button>
              {/* <Button onClick={clear}>清空</Button> */}
            </Form.Item>
          </Form>
      }

    </>
  );
};
